package wangjg.security.interceptor.spring;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import wangjg.security.core.LoginModule;
import wangjg.security.core.validator.RequestValidator;
import wangjg.security.http.HttpContext;
import wangjg.security.http.HttpRequest;

public class MvcInterceptor implements HandlerInterceptor {
	private static final Logger log = LoggerFactory.getLogger(MvcInterceptor.class);
	
	private LoginModule loginModule;
	
	private RequestValidator requestValidator;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		try{
			HttpContext.setRequest(request);
			HttpContext.setResponse(response);
			
			String servletPath = request.getServletPath();
			Object user = loginModule.login();
			HttpRequest httpRequest = new HttpRequest(servletPath);
			boolean allow = this.requestValidator.validate(httpRequest, user);
			if(!allow){
				this.responseErr(request, response);
			}
			return allow;
		} finally {
			HttpContext.setRequest(null);
			HttpContext.setResponse(null);
		}
	}
	
	protected void responseErr(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html");
		response.getWriter().print("{\"message\":\"no permission!\"}");
	}
	
	@Override
	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HttpContext.setRequest(null);
		HttpContext.setResponse(null);
	}

	public LoginModule getLoginModule() {
		return loginModule;
	}

	public void setLoginModule(LoginModule loginModule) {
		this.loginModule = loginModule;
	}

	public RequestValidator getRequestValidator() {
		return requestValidator;
	}

	public void setRequestValidator(RequestValidator requestValidator) {
		this.requestValidator = requestValidator;
	}

}
